﻿using OLMS;
using OLMS.BLL;
using OLMS.DAL;
using OLMS_MVC2.BLL;
using OLMS_MVC2.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.SessionState;


namespace OLMS_MVC2.Controllers
{
    [SessionState(SessionStateBehavior.Required)] // 确保可以使用Session
    public class ExcelController : Controller
    {
        
        // GET: Excel
        public ActionResult Index()
        {
            return View();
        }

        // GET: Excel/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Excel/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Excel/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Excel/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Excel/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Excel/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Excel/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        [HttpPost]
        public ActionResult Login(string loginId, string loginPwd, string validateCode)
        {
            // 先验证验证码
            if (Session["ValidateCode"]?.ToString() != validateCode)
            {
                TempData["ErrorMessage"] = "验证码错误";
                return View();
            }

            var user = UserBLL.Login(loginId, loginPwd);
            if (user != null)
            {
                Session["user"] = user;
                return user.RoleId != 1
                    ? RedirectToAction("MainPape")
                    : RedirectToAction("Index");
            }

            TempData["ErrorMessage"] = "登录账号或登录密码错误!";
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterViewModel model)
        {
            return View();
        }

        public ActionResult MainPape()
        {
            return View();
        }
        public ActionResult selectAllOrder()
        {
            //using (OLMSDBEntities db = new OLMSDBEntities())
            //{
            //    // 按AlbumId分组，计算每个专辑的总销售额并排序
            //    var albumSales = db.OrderDetails
            //        .GroupBy(od => od.AlbumId)  // 改为按AlbumId分组
            //        .Select(g => new OrderSummaryViewModel  // 改用新的视图模型
            //        {
            //            AlbumId = g.Key,
            //            TotalQuantity = g.Sum(od => od.Quantity),
            //            TotalRevenue = g.Sum(od => od.Quantity * od.UnitPrice),
            //            Orders = g.ToList()  // 保留原始订单明细
            //        })
            //        .OrderByDescending(a => a.TotalRevenue)  // 按总销售额降序
            //        .ToList();

            //    return View(albumSales);
            //}
            OrderDetailBLL orderDetailBLL = new OrderDetailBLL();
            List<OrderSummaryViewModel> selectAllOrder_method = orderDetailBLL.SelectAllOrderMethod();
            return View(selectAllOrder_method);
        }

        

        public ActionResult selectSaleTop()
        {
            using (OLMSDBEntities db = new OLMSDBEntities())
            {
                var albumSales = db.OrderDetails
                    .GroupBy(od => od.AlbumId)
                    .Select(g => new AlbumSalesViewModel
                    {
                        AlbumId = g.Key,
                        AlbumName = g.First().Albums.Title, // 获取专辑名称
                        TotalQuantity = g.Sum(od => od.Quantity),
                        TotalRevenue = g.Sum(od => od.Quantity * od.UnitPrice)
                    })
                    .OrderByDescending(a => a.TotalRevenue) // 按总销售额降序
                    .ThenByDescending(a => a.TotalQuantity) // 销售额相同按销量排序
                    .ToList();

                return View(albumSales);
            }
        }

        public ActionResult ExportExcel()
        {
            // 获取订单数据
            OrderDetailBLL orderDetailBLL = new OrderDetailBLL();
            List<OrderSummaryViewModel> orders = orderDetailBLL.SelectAllOrderMethod();

            // 使用DataToExcel类中的方法
            using (var excelExporter = new DataToExcel())
            {
                byte[] fileBytes = excelExporter.ExportOrders(orders);

                // 返回Excel文件
                return File(
                    fileBytes,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    $"订单汇总_{DateTime.Now:yyyyMMddHHmmss}.xlsx");
            }
        }

        [HttpGet]
        [OutputCache(NoStore = true, Duration = 0)] // 禁用缓存
        public ActionResult ValidateCode()
        {
            //// 颜色数组
            //Color[] colors = new Color[]
            //{
            //    Color.Red, Color.Green, Color.Yellow, Color.Blue,
            //    Color.AliceBlue, Color.Aqua, Color.Bisque, Color.Brown
            //};

            //// 创建图片对象
            //using (Image img = new Bitmap(100, 36))
            //using (Graphics graphics = Graphics.FromImage(img))
            //{
            //    Random random = new Random(DateTime.Now.Millisecond);

            //    // 生成4个随机字母
            //    int charNum1 = random.Next(97, 122);
            //    int charNum2 = random.Next(97, 122);
            //    int charNum3 = random.Next(97, 122);
            //    int charNum4 = random.Next(97, 122);

            //    string validCode = $"{(char)charNum1}{(char)charNum2}{(char)charNum3}{(char)charNum4}";
            //    Session["ValidateCode"] = validCode; // 存储验证码到Session

            //    // 设置字体
            //    Font font = new Font("宋体", 24);

            //    // 绘制每个字符
            //    graphics.DrawString(((char)charNum1).ToString(), font,
            //        new SolidBrush(colors[random.Next(0, colors.Length - 1)]), 7, -3);
            //    graphics.DrawString(((char)charNum2).ToString(), font,
            //        new SolidBrush(colors[random.Next(0, colors.Length - 1)]), 26, -9);
            //    graphics.DrawString(((char)charNum3).ToString(), font,
            //        new SolidBrush(colors[random.Next(0, colors.Length - 1)]), 50, 0);
            //    graphics.DrawString(((char)charNum4).ToString(), font,
            //        new SolidBrush(colors[random.Next(0, colors.Length - 1)]), 70, -7);

            //    // 输出图片
            //    MemoryStream ms = new MemoryStream();
            //    img.Save(ms, ImageFormat.Jpeg);
            //    return File(ms.ToArray(), "image/jpeg");
            //}
            // 创建验证码服务实例
            var validateCodeService = new ValidateCodeService();

            // 调用方法生成验证码图片和代码
            var (imageBytes, code) = validateCodeService.GenerateValidateCode();

            // 将验证码存入Session
            Session["ValidateCode"] = code;

            // 返回图片文件
            return File(imageBytes, "image/jpeg");
        }
    }
}
